//
//  NewsListContorller.swift
//  网易新闻
//
//  Created by wl on 15/11/12.
//  Copyright © 2015年 wl. All rights reserved.
//  新闻列表控制器，用来展示当前频道所有新闻
/***************************************************
*  如果您发现任何BUG,或者有更好的建议或者意见，请您的指教。
*邮箱:wxl19950606@163.com.感谢您的支持
***************************************************/
import UIKit
import SVProgressHUD
class NewsListContorller: UITableViewController,signDelegate{
//========================================================
// MARK: - 一些属性
//========================================================
    /// 当前频道
    var channel: String!
    /// 当前频道的url
    var channelUrl: String!
    
    //字体大小
    var size: String = "中"
    // 充当tableView的数据源
    let newsListProvider = NewsListProvider()
    var newsModelArray: [NewsModel]? {
        didSet {
            self.newsListProvider.newsModelArray = newsModelArray
            // 本地缓存
            LocalDataTool.saveNewsList(self.channelUrl, newsModelArray: self.newsModelArray!)
            self.tableView.reloadData()
        }
    }
    var hasSelected: Bool = false
    
    var newsTableHeadViewController = NewsHeadViewController()
    //设置字体视图
    var setUpfontView = SetupTableViewController()
    //签到视图
    var signView: Sign?
    var SignModel: signModel?
    var msg: regiestInfo?
    var page = 0
    var selectedPage = 0
//  ========================================================
// MARK: - 一些方法
//========================================================
    override func viewDidLoad() {
        super.viewDidLoad()
        publicMethod.setHUDStyle()        
        self.tableView.dataSource = self.newsListProvider
        self.newsListProvider.tableView = self.tableView
        
        publicMethod.hiddleExtendCellForTableView(self.tableView)
        
        self.tableView.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(NewsListContorller.requestInfo))
        self.tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: #selector(NewsListContorller.nextRequestInfo))
        
     
        // 加载本地缓存数据
        if let newsModelArray = LocalDataTool.getNewsList(self.channelUrl) {
            self.newsModelArray = newsModelArray
        }
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.adSelected(_:)), name:"adClicked_noti", object: nil)
        
        self.tableView.mj_header.beginRefreshing()

        self.newsTableHeadViewController.url = self.channelUrl
        
       self.addChildViewController(self.newsTableHeadViewController)
        
        self.tableView.tableHeaderView = self.newsTableHeadViewController.view
        
        self.newsTableHeadViewController.delegate = self
        
    }
    

    override func viewWillDisappear(animated: Bool) {
        SVProgressHUD.dismiss()
       
        super.viewWillDisappear(animated)
    }
    /**
    下拉刷新，加载最新数据
    */
    func requestInfo() {
        self.page = 0
        self.tableView.mj_footer.resetNoMoreData()
        if self.hasSelected == false{
            let urlStr = String(format: "%@infomationjson/\(self.channelUrl)",BaseUrl)
            DataTool.loadNewsDataEx(urlStr, completionHandler: { (newsArray) -> Void in
                self.tableView.mj_header.endRefreshing()
                guard let newDataes = newsArray else {
                    return
                }
                self.newsModelArray = newDataes
            })

        }else{
           // self.tableView.mj_footer.resetNoMoreData()
            self.selectedPage = 0
            if self.channelUrl == "cptj"{
                let urlStr = String(format: "%@product/dosearch",BaseUrl)
                DataTool.dropMenuScreen_cptj(self.newsTableHeadViewController.tages!, paixu: self.newsTableHeadViewController.paixu!,url: urlStr, page: String(self.selectedPage), completionHandler: { (newsArray) -> Void in
                    self.tableView.mj_header.endRefreshing()
                    guard let newDataes = newsArray else {
                        return
                    }
                    print(newDataes)
                    self.newsModelArray = newDataes
                    
                })

            }else if self.channelUrl == "hyzx"{
                let urlStr = String(format: "%@infomation/dosearch",BaseUrl)
                DataTool.dropMenuScreen_cptj(self.newsTableHeadViewController.tages!, paixu: self.newsTableHeadViewController.paixu!,url: urlStr, page: String(self.selectedPage), completionHandler: { (newsArray) -> Void in
                    self.tableView.mj_header.endRefreshing()
                    guard let newDataes = newsArray else {
                        return
                    }
                    print(newDataes)
                     self.newsModelArray = newDataes
                    
                })
            }else if self.channelUrl == "xlmx"{
                let urlStr = String(format: "%@xlmx/dosearch",BaseUrl)
                DataTool.dropMenuScreen_cptj(self.newsTableHeadViewController.tages!, paixu: self.newsTableHeadViewController.paixu!,url: urlStr, page: String(self.selectedPage), completionHandler: { (newsArray) -> Void in
                     self.tableView.mj_header.endRefreshing()
                    guard let newDataes = newsArray else {
                        return
                    }
                    print(newDataes)
                     self.newsModelArray = newDataes
                  
                })

            }
            
        }

        
    }
    
    /**
     上拉刷新，加载最新数据
     */
    func nextRequestInfo() {
        self.selectedPage += 1
        if self.hasSelected == true{
            if self.channelUrl == "cptj"{
                let urlStr = String(format: "%@product/dosearch",BaseUrl)
                DataTool.dropMenuScreen_cptj(self.newsTableHeadViewController.tages!, paixu: self.newsTableHeadViewController.paixu!,url: urlStr, page: String(self.selectedPage), completionHandler: { (newsArray) -> Void in
                     self.tableView.mj_footer.endRefreshing()
                    guard let newDataes = newsArray else {
                        return
                    }
                    if newDataes.count == 0 {
                    self.tableView.mj_footer.endRefreshingWithNoMoreData()
                    } else {
                       
                        print(newDataes)
                        self.newsModelArray! += newDataes
                    }
                   
                    
                })
                
            }
            if self.channelUrl == "hyzx"{
                let urlStr = String(format: "%@infomation/dosearch",BaseUrl)
                DataTool.dropMenuScreen_cptj(self.newsTableHeadViewController.tages!, paixu: self.newsTableHeadViewController.paixu!,url: urlStr, page: String(self.selectedPage), completionHandler: { (newsArray) -> Void in
                     self.tableView.mj_footer.endRefreshing()
                    guard let newDataes = newsArray else {
                        return
                    }
                    if newDataes.count == 0 {
                        
                    self.tableView.mj_footer.endRefreshingWithNoMoreData()
                    
                    } else {
                       
                        print(newDataes)
                        self.newsModelArray! += newDataes
                    }
                    
                    
                })

                
            }
            if self.channelUrl == "xlmx"{
                let urlStr = String(format: "%@xlmx/dosearch",BaseUrl)
                DataTool.dropMenuScreen_cptj(self.newsTableHeadViewController.tages!, paixu: self.newsTableHeadViewController.paixu!,url: urlStr, page: String(self.selectedPage), completionHandler: { (newsArray) -> Void in
                    self.tableView.mj_footer.endRefreshing()
                    guard let newDataes = newsArray else {
                        return
                    }
                    if newDataes.count == 0 {
                        
                    self.tableView.mj_footer.endRefreshingWithNoMoreData()
                        
                    } else {
                        
                        print(newDataes)
                        self.newsModelArray! += newDataes
                    }
                    
                    
                })

            }
            
            
            
        }else{
            self.page += 1
            if self.channelUrl == "cptj"{
                let url = String(format: "%@product/dosel/fenye/\(self.page)",BaseUrl)
                
                DataTool.loadNextNewsDataEx(String(self.page), urlStr: url, completionHandler: { (newsArray) -> Void in
                      self.tableView.mj_footer.endRefreshing()
                    guard let newDataes = newsArray else {
                        return
                    }
                    if newDataes.count == 0 {
                        
                    self.tableView.mj_footer.endRefreshingWithNoMoreData()
                       
                    } else {
                      
                        self.newsModelArray! += newDataes

                    }
                })
            }
            if self.channelUrl == "hyzx"{
                
                let url = String(format: "%@infomation/dosel/fenye/\(self.page)",BaseUrl)
                
                DataTool.loadNextNewsDataEx(String(self.page), urlStr: url, completionHandler: { (newsArray) -> Void in
                     self.tableView.mj_footer.endRefreshing()
                    guard let newDataes = newsArray else {
                        return
                    }
                    if newDataes.count == 0 {
                        
                    self.tableView.mj_footer.endRefreshingWithNoMoreData()
                        
                       
                    } else {
                       
                         self.newsModelArray! += newDataes
                    }
                   
                })
                
            }
            if self.channelUrl == "xlmx"{
                
                let url = String(format: "%@infomation/xlmx/dosel/fenye/\(self.page)",BaseUrl)
                DataTool.loadNextNewsDataEx(String(self.page), urlStr: url, completionHandler: { (newsArray) -> Void in
                     self.tableView.mj_footer.endRefreshing()
                    guard let newDataes = newsArray else {
                        return
                    }
                    if newDataes.count == 0 {
                        self.tableView.mj_footer.endRefreshingWithNoMoreData()
                        
                    } else {
                        
                       
                        self.newsModelArray! += newDataes
                    }
                    
                })
                
            }

            
        }
        
    }
   

    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
       UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent
        
        if ApplicationDelegate.isLogin(){
            let phone = publicMethod.userName()
            let pass = publicMethod.passWord()
            let token = publicMethod.token()
            DataTool.login(phone, pass: pass, token: token, completionHandler: { (newModel) in
                guard let newDataes = newModel else {
                    return
                }
                print(newDataes)
                
            })
            
        }
        self.tabBarController?.tabBar.hidden = false
        self.tableView.tableHeaderView?.frame.size.height = HeadViewHeight
    
    }
    
    override func viewDidAppear(animated: Bool) {
      
       self.edgesForExtendedLayout = UIRectEdge.None
        
    }


}

// MARK: - Table view 代理
extension NewsListContorller:CellAttributeProtocol {
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        return provideCellHeight(self.newsModelArray!, indexPath: indexPath)
    }
    
    
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        if(cell.respondsToSelector(Selector("setSeparatorInset:"))) {
            cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0)
        }
        if(cell.respondsToSelector(Selector("setLayoutMargins:"))) {
            cell.layoutMargins = UIEdgeInsetsMake(0, 0, 0, 0)
        }
    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        //取消选中
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        
        let vc = provideSelectedNewsVc(self.newsModelArray!, indexPath: indexPath)
        vc.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(vc, animated: true)
        if let interactivePopGestureRecognizer = self.navigationController?.interactivePopGestureRecognizer {
            interactivePopGestureRecognizer.delegate = nil
        }
        
    }
}

    // MARK: - CyclePictureViewDelegate
extension NewsListContorller: CyclePictureViewDelegate {
    /**
    当头部滚动新闻点击的时候被调用
    */

    func cyclePictureView(cyclePictureView: CyclePictureView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let index = indexPath.row
        
        // 取出新闻模型
        let newsModel = self.newsModelArray![0]
        // 取出对应图片的模型
        if index == 0 {
            //do nothing
        }else if let ads = newsModel.ads?[index - 1] {
            //newsModel.photosetID = ads.url
            newsModel.title = ads.title
            newsModel.docid = ads.docid
            newsModel.specialID = ads.specialID
        }
        
        let vc = provideVcWithNewsModel(newsModel)
        
        self.navigationController?.pushViewController(vc, animated: true)
        if let interactivePopGestureRecognizer = self.navigationController?.interactivePopGestureRecognizer {
            interactivePopGestureRecognizer.delegate = nil
        }
    }
    
    func industryChangeClick() -> Void {
        print("行业切换")
        
    }
    func signClick(sender: UIButton) -> Void {
        //应该调接口
        let btn: UIButton = sender
        btn.selected = !btn.selected
        if btn.selected{
            print("签到")
            if ApplicationDelegate.isLogin(){
                self.tableView.setContentOffset(CGPointMake(0, 0), animated: false)
                self.checkInSign()
                signView = Sign.init(frame: kScreen_frame)
                signView?.delegate = self
                
                self.view.addSubview(signView!)
                
            }else{
                let sb = UIStoryboard(name: "Login", bundle: nil)
                let vc = sb.instantiateViewControllerWithIdentifier("LoginViewController")
                self.navigationController?.pushViewController(vc, animated: true)
            }
        }else{
            signView?.closeBtnClick()
        }
        
    
        
    }
    func searchClick() -> Void {
        print("搜索")
        let sb = (UIStoryboard.init(name: "Search", bundle: nil))
        let vc = (sb.instantiateViewControllerWithIdentifier("SearchViewController"))
       self.navigationController?.pushViewController(vc, animated: true)
    }
    //MARK:signViewDelegate
    func signBtnClicked(sender: UIButton){
        //调接口
        
        self.signSelected()

    }
    //MARK:NWTWORKING
    func checkInSign(){
        DataTool.signInfo({ (newModel) in
            guard newModel != nil else {
                return
            }
            self.SignModel = newModel
            self.signView!.model = self.SignModel
        })
    }
    
    func signSelected(){
        DataTool.sign({ (newModel) in
            guard newModel != nil else {
                return
            }
            self.msg = newModel
            self.checkInSign()
            SVProgressHUD.showSuccessWithStatus(self.msg?.msg)
           
        })
    }
    
    func adSelected(nsnotification: NSNotification) {
        print("广告点击")
        let url = nsnotification.object?.valueForKey("url") as? String
       
        let vc = self.storyboard?.instantiateViewControllerWithIdentifier("DetailTaoboaAndliveVideoVC") as! DetailTaoboaAndliveVideoVC
        
        vc.urlStr = url!
        self.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(vc, animated: true)
        self.hidesBottomBarWhenPushed = false


    }
}

extension NewsListContorller: HeardDelegate {
    func onHeightChange(newView: UIView) {
        self.tableView.tableHeaderView = newView
    }
    func setContentViewControllerWithInfo() -> Void{
       // self.newsModelArray = cellInfo
        self.hasSelected = true
        self.requestInfo()
        
    }
    func setContentTransferViewControllerWithInfo() -> Void{
        
    }
    func setContentJoninUsViewControllerWithInfo() -> Void{
        
    }
    func setContentMXQYViewConreollerWithInfo() -> Void{
        
    }
    func setContentZYCPViewControllerWithInfo() -> Void{
        
    }
    func CyclePictureViewSelected(url: String){
        let vc = self.storyboard?.instantiateViewControllerWithIdentifier("DetailTaoboaAndliveVideoVC") as! DetailTaoboaAndliveVideoVC
        
        vc.urlStr = url
        self.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(vc, animated: true)
        self.hidesBottomBarWhenPushed = false
    }
}

enum RequestType {
    case Default //上拉加载数据
    case Recommend // 热点数据
    case MoreInfo  // 下拉加载数据
}

extension String {
    
    func channelKey() -> String {
        if self.characters.count == 0 {
            return "";
        }
        
        let index = self.rangeOfString("/")
        let key = self.substringFromIndex(index!.endIndex)
        return key
    }
}
// 版权属于原作者
// http://code4app.com (cn) http://code4app.net (en)
// 发布代码于最专业的源码分享网站: Code4App.com